﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tetris.Blocks;
using Tetris.Grid;

namespace Tetris
{
    public class BlockGrid
    {
        private int m_width;
        public int width
        {
            get
            {
                return m_width;
            }
        }

        private int m_height;
        public int height
        {
            get
            {
                return m_height;
            }
        }

        private Block[,] m_grid;

        public BlockGrid(int width, int height)
        {
            m_width = width;
            m_height = height;

            m_grid = new Block[m_width, m_height];
            for (int col = 0; col < m_width; col++)
            {
                for (int row = 0; row < m_height; row++)
                    SetCell(new GridPosition(col, row), null);
            }
        }

        public bool IsEmpty(GridPosition gridPosition)
        {
            return (m_grid[gridPosition.col, gridPosition.row] == null);
        }

        public bool ContainsStaticBlock(GridPosition gridPosition)
        {
            if (!ValidGridPosition(gridPosition))
                throw new ArgumentOutOfRangeException("Invalid row or column for this grid.");

            // grid position is empty
            if (IsEmpty(new GridPosition(gridPosition.col, gridPosition.row)))
                return false;
            else if (m_grid[gridPosition.col, gridPosition.row].IsStatic())
                return true;
            else
                return false;
        }

        public void SetCell(GridPosition gridPosition, Block block)
        {
            if (!ValidGridPosition(gridPosition))
                throw new ArgumentOutOfRangeException("Invalid row or column for this grid.");

            m_grid[gridPosition.col, gridPosition.row] = block;
        }

        public Block BlockAt(GridPosition gridPosition)
        {
            if (!ValidGridPosition(gridPosition))
                throw new ArgumentOutOfRangeException("Invalid row or column for this grid.");

            return m_grid[gridPosition.col, gridPosition.row];
        }

        public bool ValidGridPosition(GridPosition gridPosition)
        {
            if (gridPosition.row < 0 || gridPosition.row >= m_height || gridPosition.col < 0 || gridPosition.col >= m_width)
                return false;
            else
                return true;
        }
    }
}
